<?php

namespace app\gov\controller;

use app\gov\model\UserAreaModel;
use app\merchant\model\MerchantModel;
use app\task\model\CategoryModel;
use app\task\model\TaskModel;
use think\admin\Controller;
use think\admin\extend\DataExtend;
use think\admin\service\AdminService;
use think\facade\Db;

/**
 * 订单任务管理
 * @class Task
 * @package app\gov\controller
 */
class Task extends Controller
{
    /**
     * 订单任务列表
     * @auth true
     * @menu true
     */
    public function index()
    {
        $this->category_list = CategoryModel::field('id,name')->order('sort desc, id desc')->select()->toArray();
        $this->merchant_list = MerchantModel::field('id,nickname,company')->order('id desc')->select()->toArray();
        $this->task_status_dict = TaskModel::TASK_STATUS_DICT;
        $this->title = '订单任务列表';
        $query = TaskModel::mQuery()->alias('t')->where('t.is_deleted', 0)->where('t.status', 1)
            ->whereNotIn('t.task_status', [TaskModel::TASK_STATUS__REVIEW_FAILED, TaskModel::TASK_STATUS__CANCELED])
            ->with(['category','merchant', 'transport'])
            ->field('t.*')
            ->join('task_category tc', 'tc.id=t.category_id', 'left')
            ->join('merchant m', 'm.id=t.merchant_id', 'left')
            ->join('task_transport tr', 'tr.task_id=t.id', 'left')
            ->like('t.name#name,tr.type#transport_type,tr.scene#transport_scene')
            ->equal('t.category_id#category_id,m.merchant_id#merchant_id,t.gov_review_status#gov_review_status')
            ->dateBetween('t.create_at#create_at,t.exec_at#exec_at');

        // 获取登录用户，判断权限
        $user = $this->app->session->get('user');
        if ($user['usertype'] != 'feitu_admin'){
            $user_area = UserAreaModel::where('gov_user_id', $user['id'])->find();
            if (empty($user_area)) $this->error('请先设置审批地区');
            $query->where('t.province', $user_area['province'])->where('t.city', $user_area['city']);
        }
        // 列表数据渲染
        $query->layTable();
    }

    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _index_page_filter(array &$data)
    {
        foreach ($data as &$vo){
            if(isset($vo['task_status'])) $vo['task_status_text'] = TaskModel::TASK_STATUS_DICT[$vo['task_status']] ?? '';
         }
    }

    /**
     * 编辑订单任务
     * @auth true
     */
    public function edit()
    {
//        $this->_applyFormToken();
        TaskModel::mForm('form');
    }

    /**
     * 表单数据处理
     * @param array $vo
     */
    protected function _edit_form_filter(array &$vo)
    {
        if ($this->request->isGet()) {
            $this->category_list = CategoryModel::field('id,name')->order('sort desc, id desc')->select()->toArray();
            $this->merchant_list = MerchantModel::field('id,nickname,company')->order('id desc')->select()->toArray();
            $area_list = Db::name('Area')->order('id asc')->column('id,pid,ext_name as name');
            $this->area_list = DataExtend::arr2tree($area_list, 'id', 'pid','children');
            // 存在merchant_id
            if (empty($vo) && !empty($this->request->get('merchant_id'))){
                $vo['merchant_id'] = $this->request->get('merchant_id');
            }
            if(!empty($this->request->get('id'))){
                $task = TaskModel::with('transport')->where('is_deleted', 0)->where('id', $this->request->get('id'))->find()->toArray();
                if ($task['category_id'] == 1){
                    $transport = $task['transport'];
                    $task['start_at'] = $transport['start_at'] ?? '';
                    $task['end_at'] = $transport['end_at'] ?? '';
                    $task['transport_type'] = $transport['type'] ?? '';
                    $task['transport_scene'] = $transport['scene'] ?? '';
                    $task['transport_distance'] = $transport['distance'] ?? '';
                    $task['weight'] = $transport['weight'] ?? '';
                    $task['province'] = $transport['province'] ?? '';
                    $task['city'] = $transport['city'] ?? '';
                    $task['area'] = $transport['area'] ?? '';
                    $task['address'] = $transport['address'] ?? '';
                    $task['place'] = $transport['place'] ?? '';
                    $task['lat'] = $transport['lat'] ?? '';
                    $task['lng'] = $transport['lng'] ?? '';
                    $task['latlng'] = $transport['latlng'] ?? '';
                    $task['province2'] = $transport['province2'] ?? '';
                    $task['city2'] = $transport['city2'] ?? '';
                    $task['area2'] = $transport['area2'] ?? '';
                    $task['address2'] = $transport['address2'] ?? '';
                    $task['place2'] = $transport['place2'] ?? '';
                    $task['lat2'] = $transport['lat2'] ?? '';
                    $task['lng2'] = $transport['lng2'] ?? '';
                    $task['latlng2'] = $transport['latlng2'] ?? '';
                    $task['transport_type_other'] = $transport['type_other'] ?? '';
                    $task['transport_scene_other'] = $transport['scene_other'] ?? '';
                }
                $vo = $task;
            }else{
                $vo['category_id'] =  1;
            }
        } else {
            $id = $this->request->post('id');
            $task = TaskModel::where('is_deleted', 0)->where('id', $id)->lock(true)->find();
            if (empty($task)) $this->error('订单任务不存在');
            $vo['file_name'] = '审批文件';
            if (empty($vo['file'])) $this->error('请上传审批文件');
        }
    }

    /**
     * 订单任务详情
     * @auth true
     */
    public function detail()
    {
        $this->category_list = CategoryModel::field('id,name')->order('sort desc, id desc')->select()->toArray();
        $this->merchant_list = MerchantModel::field('id,nickname,company')->order('id desc')->select()->toArray();
        $task = TaskModel::with('transport')->where('id', $this->request->get('id'))->find()->toArray();
        if ($task['category_id'] == 1){
            $transport = $task['transport'];
            $task['start_at'] = $transport['start_at'] ?? '';
            $task['end_at'] = $transport['end_at'] ?? '';
            $task['transport_type'] = $transport['type'] ?? '';
            $task['transport_scene'] = $transport['scene'] ?? '';
            $task['transport_distance'] = $transport['distance'] ?? '';
            $task['weight'] = $transport['weight'] ?? '';
            $task['province'] = $transport['province'] ?? '';
            $task['city'] = $transport['city'] ?? '';
            $task['area'] = $transport['area'] ?? '';
            $task['address'] = $transport['address'] ?? '';
            $task['place'] = $transport['place'] ?? '';
            $task['lat'] = $transport['lat'] ?? '';
            $task['lng'] = $transport['lng'] ?? '';
            $task['latlng'] = $transport['latlng'] ?? '';
            $task['province2'] = $transport['province2'] ?? '';
            $task['city2'] = $transport['city2'] ?? '';
            $task['area2'] = $transport['area2'] ?? '';
            $task['address2'] = $transport['address2'] ?? '';
            $task['place2'] = $transport['place2'] ?? '';
            $task['lat2'] = $transport['lat2'] ?? '';
            $task['lng2'] = $transport['lng2'] ?? '';
            $task['latlng2'] = $transport['latlng2'] ?? '';
            $task['transport_type_other'] = $transport['type_other'] ?? '';
            $task['transport_scene_other'] = $transport['scene_other'] ?? '';
        }
        $this->vo = $task;
        $this->fetch();
    }

    /**
     * 审核订单任务
     * @auth true
     */
    public function review()
    {
        if ($this->request->isGet()){
            $this->category_list = CategoryModel::field('id,name')->order('sort desc, id desc')->select()->toArray();
            $this->merchant_list = MerchantModel::field('id,nickname,company')->order('id desc')->select()->toArray();

            $task = TaskModel::with('transport')->where('is_deleted', 0)->where('id', $this->request->get('id'))->find()->toArray();
            if ($task['category_id'] == 1){
                $transport = $task['transport'];
                $task['start_at'] = $transport['start_at'] ?? '';
                $task['end_at'] = $transport['end_at'] ?? '';
                $task['transport_type'] = $transport['type'] ?? '';
                $task['transport_scene'] = $transport['scene'] ?? '';
                $task['transport_distance'] = $transport['distance'] ?? '';
                $task['weight'] = $transport['weight'] ?? '';
                $task['province'] = $transport['province'] ?? '';
                $task['city'] = $transport['city'] ?? '';
                $task['area'] = $transport['area'] ?? '';
                $task['address'] = $transport['address'] ?? '';
                $task['place'] = $transport['place'] ?? '';
                $task['lat'] = $transport['lat'] ?? '';
                $task['lng'] = $transport['lng'] ?? '';
                $task['latlng'] = $transport['latlng'] ?? '';
                $task['province2'] = $transport['province2'] ?? '';
                $task['city2'] = $transport['city2'] ?? '';
                $task['area2'] = $transport['area2'] ?? '';
                $task['address2'] = $transport['address2'] ?? '';
                $task['place2'] = $transport['place2'] ?? '';
                $task['lat2'] = $transport['lat2'] ?? '';
                $task['lng2'] = $transport['lng2'] ?? '';
                $task['latlng2'] = $transport['latlng2'] ?? '';


                $task['transport_type_other'] = $transport['type_other'] ?? '';
                $task['transport_scene_other'] = $transport['scene_other'] ?? '';
            }
            $this->vo = $task;
            $this->fetch();
        }else{
            $id = $this->request->post('id');
            $gov_review_status = $this->request->post('gov_review_status');
            $review_reason = $this->request->post('gov_review_reason');
            $task = TaskModel::where('is_deleted', 0)->where('id', $id)->lock(true)->find();
            if (empty($task)) $this->error('订单任务不存在');
            if ($task->gov_review_status != 0) $this->error('待审核的订单任务才能审核');
            if (!in_array($gov_review_status, [1, -1])) $this->error('审核状态不正确');
//            if ($gov_review_status == -1 && empty($review_reason)) $this->error('请填写审核不通过的原因');

            // 获取登录用户，判断权限
            $user = $this->app->session->get('user');
            if ($user['usertype'] != 'feitu_admin'){
                $user_area = UserAreaModel::where('gov_user_id', $user['id'])->find();
                if (empty($user_area)) $this->error('您还没有设置审批地区');
                if($task->province != $user_area['province'] || $task->city != $user_area['city']){
                    $this->error('您没有审批该订单任务的权限');
                }
            }

            TaskModel::mSave([
                'id' => $id,
                'gov_review_status' => $gov_review_status,
                'gov_review_reason' => $review_reason,
                'gov_review_at' => date('Y-m-d H:i:s'),
                'gov_review_admin_id' => AdminService::getUserId(),
            ]);
        }
    }

    /**
     * 批量审核订单任务
     * @auth true
     */
    public function review_batch()
    {
        if ($this->request->isPost()){
            $ids = str2arr($this->request->post('id'));
            foreach ($ids as $id){
                $gov_review_status = $this->request->post('gov_review_status');
                $review_reason = $this->request->post('gov_review_reason');
                $task = TaskModel::where('is_deleted', 0)->where('id', $id)->lock(true)->find();
                if (empty($task)) $this->error('订单任务不存在');
                if ($task->gov_review_status != 0) $this->error('待审核的订单任务才能审核');
                if (!in_array($gov_review_status, [1, -1])) $this->error('审核状态不正确');

                // 获取登录用户，判断权限
                $user = $this->app->session->get('user');
                if ($user['usertype'] != 'feitu_admin'){
                    $user_area = UserAreaModel::where('gov_user_id', $user['id'])->find();
                    if (empty($user_area)) $this->error('您还没有设置审批地区');
                    if($task->province != $user_area['province'] || $task->city != $user_area['city']){
                        $this->error('您没有审批该订单任务的权限');
                    }
                }
                $task->save([
                    'gov_review_status' => $gov_review_status,
                    'gov_review_reason' => $review_reason,
                    'gov_review_at' => date('Y-m-d H:i:s'),
                    'gov_review_admin_id' => AdminService::getUserId(),
                ]);
            }
            $this->success('保存成功');
        }else{
            $this->error('请求方式不正确');
        }
    }


    /**
     * 重新提交审核
     * @auth true
     */
    public function apply_review()
    {
        $id = $this->request->post('id');
        $task = TaskModel::where('is_deleted', 0)->where('id', $id)->lock(true)->find();
        if (empty($task)) $this->error('订单任务不存在');
        if ($task->gov_review_status != -1) $this->error('被驳回的订单才能重新提交审核');
        $task->save([
            'gov_review_status' => 0,
        ]);
        $this->success('已重新提交审核');
    }
}
